<template>
  <view>
    <view class="addPatient">
      <view class="add-icon" @click="addPatientHandle"></view>
    </view>
    <view class="order-list" v-if="list.length > 0">
      <view
        class="order-card"
        :key="index"
        style="position: relative"
        v-for="(item, index) in list">
        <view style="width: 90%">
          <view class="title-and-status">
            <view class="title-left">
              <view class="title-main">{{ item.patientName }}</view>
              <view class="title-main">{{ item.patientSex }}</view>
              <view class="title-main">{{ item.patientMedical }}</view>
              <view class="title-main">{{ item.patientPdiagnose }}</view>
            </view>
          </view>
          <view class="title-and-status">
            <view class="title-left">
              <view class="title-main">{{ item.createUser }}</view>
              <view class="title-main">{{ item.patientPhone }}</view>
            </view>
          </view>
          <view class="cycle-and-price">
            <view class="cycle">地址：{{ item.patientAddress }}</view>
          </view>
        </view>
        <view class="div-line" />
        <view class="service-btn">
          <view class="my-btn" @click="delHandle(item.patientId)">删除</view>
          <view class="my-btn" @click="editHandle(item.patientId)">修改</view>
          <view class="my-btn btn-green" @click="choosePayient(item)">
            选择
          </view>
        </view>
      </view>
    </view>

    <uni-popup ref="servicePopup" type="bottom">
      <view class="service-popup-view">
        <view class="title-view">
          <view class="title">{{ formTitle }}</view>
          <view class="close-btn-view" @click="closeServicePopup">
            <image src="../../static/pop_close.png" class="close-btn"></image>
          </view>
        </view>

        <view>
          <scroll-view scroll-y="true">
            <view class="upload-id-card-view" v-if="value != null">
              <view class="title">上传身份证</view>
              <view class="card-view">
                <view class="card-item">
                  <image
                    v-if="!form.idCardFront"
                    src="../../../static/item_idcard_front.png"
                    class="card-img"
                    @click="onIdCardFrontClick()"></image>
                  <image
                    v-else
                    :src="form.idCardFront"
                    class="card-img"
                    @click="onIdCardFrontClick()"></image>
                  <view class="tip-text">身份证正面</view>
                </view>
                <view class="card-item">
                  <image
                    v-if="!form.idCardReverse"
                    src="../../../static/item_idcard_back.png"
                    class="card-img"
                    @click="onIdCardReverseClick()"></image>
                  <image
                    v-else
                    :src="form.idCardReverse"
                    class="card-img"
                    @click="onIdCardReverseClick()"></image>
                  <view class="tip-text">身份证反面</view>
                </view>
              </view>
            </view>
            <view class="form-item-row">
              <view class="label required-label">姓名</view>
              <view class="form-item">
                <view class="input-view">
                  <input
                    v-model="form.patientName"
                    placeholder-class="placeholder-class"
                    placeholder="请输入姓名" />
                </view>
              </view>
            </view>
            <view class="form-item-row">
              <view class="label required-label">性别</view>
              <view class="form-item">
                <view class="input-view">
                  <input
                    v-model="form.patientSex"
                    placeholder-class="placeholder-class"
                    placeholder="请输入性别" />
                </view>
              </view>
            </view>
            <view class="form-item-row">
              <view class="label required-label">身份证号</view>
              <view class="form-item">
                <view class="input-view">
                  <input
                    v-model="form.nurseIdcard"
                    placeholder-class="placeholder-class"
                    placeholder="请输入身份证号" />
                </view>
              </view>
            </view>
            <view class="form-item-row">
              <view class="label required-label">出生日期</view>
              <view class="form-item">
                <view class="input-view">
                  <input
                    v-model="form.nurseBirthday"
                    placeholder-class="placeholder-class"
                    placeholder="请输入出生日期（格式：YYYY-MM-DD）" />
                </view>
              </view>
            </view>
            <view class="form-item-row">
              <view class="label required-label">地址</view>
              <view class="form-item">
                <view class="input-view">
                  <input
                    v-model="form.patientAddress"
                    placeholder-class="placeholder-class"
                    placeholder="请输入地址" />
                </view>
              </view>
            </view>
            <view class="form-item-row">
              <view class="label required-label">年龄</view>
              <view class="form-item">
                <view class="input-view">
                  <input
                    v-model="form.patientAge"
                    placeholder-class="placeholder-class"
                    placeholder="自动计算"
                    readonly />
                </view>
              </view>
            </view>
            <view class="form-item-row">
              <view class="label required-label">体重</view>
              <view class="form-item">
                <view class="input-view">
                  <input
                    v-model="form.patientWeight"
                    placeholder-class="placeholder-class"
                    placeholder="体重(kg)" />
                </view>
              </view>
            </view>
            <view class="form-item-row">
              <view class="label required-label">自理情况</view>
              <view class="form-item">
                <view class="input-view">
                  <picker
                    mode="selector"
                    :range="['可以自理', '无法自理']"
                    @change="onSelfCareAbilityChange">
                    <view
                      class="placeholder-class"
                      v-if="!form.patientPdiagnose">
                      请选择
                    </view>
                    <view class="selector-text" v-else>
                      {{ form.patientPdiagnose }}
                    </view>
                  </picker>
                </view>
              </view>
            </view>
            <view class="form-item-row">
              <view class="label required-label">联系人</view>
              <view class="form-item">
                <view class="input-view">
                  <input
                    v-model="form.createUser"
                    placeholder-class="placeholder-class"
                    placeholder="联系人" />
                </view>
              </view>
            </view>
            <view class="form-item-row">
              <view class="label required-label">联系电话</view>
              <view class="form-item">
                <view class="input-view">
                  <input
                    v-model="form.patientPhone"
                    placeholder-class="placeholder-class"
                    placeholder="请输入联系电话" />
                </view>
              </view>
            </view>
            <view class="bottom-view">
              <view class="save-btn" @click="handleSave">保存</view>
            </view>
          </scroll-view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import {
  getPatient,
  savePatient,
  getPatientById,
  delPatientById,
  editPatient,
} from "../../common/api/index.js";
import * as upload from "../../common/upload.js";

export default {
  props: {
    isInIndex: false,
  },
  data() {
    return {
      tabs: ["全部", "待支付", "服务中", "已完成", "已取消"],
      current: 0,
      orderStatus: "全部",
      status: "",
      readForm: {},
      formTitle: "添加被护理人",
      form: {
        selfCareAbility: "",
        createBy: "",
        remark: "",
        patientAddress: "",
        patientAge: "",
        patientMedical: "",
        patientName: "",
        patientPdiagnose: "",
        patientPhone: "",
        patientRemark: "",
        patientSex: "",
        patientWeight: "",
        remark: "",
        idCardFront: "",
        idCardReverse: "",
        nurseIdcard: "",
        nurseBirthday: "",
      },
      list: [],
      values: "",
    };
  },
  watch: {
    // 监听出生日期变化自动计算年龄
    "form.nurseBirthday"(newVal) {
      if (newVal) {
        this.form.patientAge = this.calculateAge(newVal);
      } else {
        this.form.patientAge = "";
      }
    },
  },
  onLoad(opt) {
    console.log("进来了添加被护理人", opt);
    this.values = opt.values;
    this.initList();
  },
  methods: {
    // 计算年龄方法
    calculateAge(nurseBirthday) {
      try {
        const birth = new Date(nurseBirthday);
        const today = new Date();

        // 验证日期有效性
        if (isNaN(birth.getTime())) {
          uni.showToast({
            title: "出生日期格式错误，请使用YYYY-MM-DD",
            icon: "none",
          });
          return "";
        }

        let age = today.getFullYear() - birth.getFullYear();
        const birthMonth = birth.getMonth();
        const todayMonth = today.getMonth();

        // 处理未过当年生日的情况
        if (todayMonth < birthMonth) {
          age--;
        } else if (todayMonth === birthMonth) {
          const birthDay = birth.getDate();
          const todayDay = today.getDate();
          if (todayDay < birthDay) {
            age--;
          }
        }

        return age < 0 ? 0 : age;
      } catch (error) {
        console.error("年龄计算失败:", error);
        return "";
      }
    },
    // 上传身份证正面
    onIdCardFrontClick() {
      const self = this; // 保存this指向
      uni.chooseImage({
        success(res) {
          upload
            .uploadIdCardFiles(res.tempFilePaths[0])
            .then((result) => {
              uni.showToast({ icon: "success", title: "上传成功" });
              self.form.idCardFront = result.data.url;
              self.form.nurseIdcard = result.data.idInfo.num;
              self.form.patientSex = result.data.idInfo.sex;
              self.form.nurseBirthday = result.data.idInfo.birth;
              self.form.patientName = result.data.idInfo.name;
              self.form.patientAddress = result.data.idInfo.address;
              // 手动触发年龄计算
              self.form.patientAge = self.calculateAge(self.form.nurseBirthday);
            })
            .catch((error) => {
              uni.showToast({
                icon: "none",
                title: `上传失败: ${error.message || JSON.stringify(error)}`,
              });
            });
        },
      });
    },
    // 上传身份证反面
    onIdCardReverseClick() {
      const self = this; // 保存this指向
      uni.chooseImage({
        success(res) {
          upload
            .uploadImageFiles(res.tempFilePaths[0]) // 确保上传方法正确接收文件路径
            .then((result) => {
              uni.showToast({ icon: "success", title: "上传成功" });
              self.form.idCardReverse = result.data.url; // 正确赋值到form
              console.log("身份证反面地址:", self.form.idCardReverse);
            })
            .catch((error) => {
              uni.showToast({
                icon: "none",
                title: `上传失败: ${error.message || JSON.stringify(error)}`,
              });
            });
        },
      });
    },
    // 上传身份证反面（修复重复打开窗口问题）
    // onIdCardReverseClick() {
    //   const self = this;
    //   // 只执行一次图片选择
    //   uni.chooseImage({
    //     count: 1, // 限制只能选择1张
    //     sizeType: ['original', 'compressed'], // 允许原图和压缩图
    //     sourceType: ['album', 'camera'], // 允许相册和相机
    //     success(res) {
    //       const tempFilePath = res.tempFilePaths[0];
    //       // 调用上传函数时，直接传入已选择的图片路径，确保上传函数内部不再执行选择
    //       upload.uploadImageFiles(tempFilePath)
    //         .then((result) => {
    //           uni.showToast({ icon: "success", title: "上传成功" });
    //           self.form.idCardReverse = result.data.url;
    //           console.log("身份证反面地址:", self.form.idCardReverse);
    //         })
    //         .catch((error) => {
    //           uni.showToast({
    //             icon: "none",
    //             title: `上传失败: ${error.message || JSON.stringify(error)}`,
    //           });
    //         });
    //     },
    //     fail(err) {
    //       console.error("选择图片失败:", err);
    //     }
    //   });
    // }

    tabClick(item, index) {
      this.current = index;
      this.orderStatus = item;
    },
    closeServicePopup() {
      this.$refs.servicePopup.close();
    },
    onSelfCareAbilityChange(e) {
      this.form.patientPdiagnose = ["可以自理", "无法自理"][e.detail.value];
    },
    // 初始化列表
    initList() {
      const userId = uni.getStorageSync("USER_ID");
      getPatient({ patientUserId: userId }).then((res) => {
        this.list = res.data.data || [];
      });
    },
    // 刷新列表
    refresh() {
      this.list = [];
      this.initList();
    },
    // 添加被护理人
    addPatientHandle() {
      this.formTitle = "添加被护理人";
      this.formStatus = "add";
      this.form = {
        ...this.form,
        idCardFront: "",
        idCardReverse: "",
        nurseIdcard: "",
        nurseBirthday: "",
        patientAge: "",
        patientName: "",
        patientSex: "",
        patientAddress: "",
      };
      this.$refs.servicePopup.open();
    },
    // 删除
    delHandle(id) {
      uni.showModal({
        title: "提示",
        content: "确认删除该条数据?",
        success: (res) => {
          if (res.confirm) {
            delPatientById({ patientId: id })
              .then((result) => {
                uni.showToast({ title: result.data.msg });
                this.refresh();
              })
              .catch(console.error);
          }
        },
      });
    },
    // 编辑
    editHandle(id) {
      this.formTitle = "编辑被护理人";
      this.formStatus = "edit";
      getPatientById({ patientId: id })
        .then((result) => {
          console.log(result);

          this.form = { ...result.data.data };
          // 编辑时重新计算年龄确保准确性
          if (this.form.nurseBirthday) {
            this.form.patientAge = this.calculateAge(this.form.nurseBirthday);
          }
          // 确保身份证反面地址正确赋值（解决回显问题）
          console.log("编辑时身份证反面:", this.form.idCardReverse);
        })
        .catch(console.error);
      this.$refs.servicePopup.open();
    },
    // 保存
    handleSave() {
      const userId = uni.getStorageSync("USER_ID");
      const openid = uni.getStorageSync("openid_key");
      const param = { ...this.form, patientUserId: userId, openid: openid };
      // if (!this.checkForm()) return;

      if (this.formStatus === "add") {
        savePatient(param).then((res) => {
          if (res.data.code === 200) {
            uni.showToast({ title: res.data.msg });
            this.closeServicePopup();
            this.initList();
          }
        });
      } else {
        editPatient(param).then((res) => {
          if (res.data.code === 200) {
            uni.showToast({ title: res.data.msg });
            this.closeServicePopup();
            this.initList();
          }
        });
      }
    },
    // 表单验证
    checkForm() {
      let msg = "";
      const showMsg = () => {
        if (msg) uni.showToast({ title: msg, icon: "none" });
      };
      if (!this.form.patientName) {
        msg = "姓名不能为空";
        showMsg();
        return false;
      }
      if (!this.form.patientSex) {
        msg = "性别不能为空";
        showMsg();
        return false;
      }
      if (!this.form.nurseBirthday) {
        msg = "出生日期不能为空";
        showMsg();
        return false;
      }
      if (!this.form.patientAge) {
        msg = "年龄计算失败，请检查出生日期";
        showMsg();
        return false;
      }
      if (!this.form.patientWeight) {
        msg = "体重不能为空";
        showMsg();
        return false;
      }
      if (!this.form.patientPdiagnose) {
        msg = "自理情况不能为空";
        showMsg();
        return false;
      }
      if (!this.form.createUser) {
        msg = "联系人不能为空";
        showMsg();
        return false;
      }
      if (!this.form.patientPhone) {
        msg = "联系电话不能为空";
        showMsg();
        return false;
      }
      if (!this.form.patientAddress) {
        msg = "服务地址不能为空";
        showMsg();
        return false;
      }
      return true;
    },
    // 选择被护理人
    choosePayient(item) {
      this.$store.commit("page/setPageInfo", {
        choosePatient: true,
        choosePatientInfo: item,
      });
      uni.navigateBack();
    },
  },
};
</script>

<style lang="scss" scoped>
page {
  background: #f9f9f9;
}

.main-container {
  display: flex;
  flex-direction: column;
}

.top-tab-bar {
  padding: 20rpx 30rpx;
  box-sizing: border-box;
  display: grid;
  grid-template-columns: repeat(auto-fit, 150rpx);
  grid-template-rows: repeat(auto-fit, 66rpx);
  grid-column-gap: 20rpx;
  grid-row-gap: 26rpx;
  background: #f9f9f9;

  // position: sticky;
  // top: 0;
  // z-index: 2;
  .tab-item {
    width: 150rpx;
    height: 66rpx;
    background: #f1f1f1;
    border-radius: 32rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    color: rgba(35, 35, 35, 0.8);
    font-size: 26rpx;
  }

  .tab-item-selected {
    background: #dff0ef;
    color: #0bc5ae;
  }
}

.order-card {
  margin-right: 30rpx;
  margin-left: 30rpx;
  background: white;
  padding: 30rpx;
  box-sizing: border-box;
  border-radius: 16rpx;
  margin-top: 20rpx;
  display: flex;
  flex-direction: column;

  .title-and-status {
    display: flex;
    width: 100%;
    justify-content: space-between;
    padding: 10rpx 0;

    .title-left {
      display: flex;
      justify-content: flex-start;
      // width: 50%;
      align-items: flex-end;

      .title-main {
        color: #333333;
        font-size: 26rpx;
        font-weight: 700;
        margin-right: 30rpx;
      }

      .subhead {
        color: #747474;
        font-size: 28rpx;
      }
    }

    .time {
      flex: 1;
      color: rgba(35, 35, 35, 0.7);
      font-size: 26rpx;
    }

    .status {
      font-size: 30rpx;
      color: #747474;
    }
  }

  .item-tag {
    display: flex;
    justify-content: flex-start;
    // width: 80%;
    align-items: center;
    margin-top: 20rpx;
    flex-wrap: wrap;

    .service-tag {
      width: 110rpx;
      background-color: #eafaf5;
      font-size: 20rpx;
      color: #6f7070;
      padding: 5rpx;
      height: 50rpx;
      line-height: 50rpx;
      text-align: center;
      border-radius: 25rpx;
      margin-right: 10rpx;
      margin-bottom: 10rpx;
    }
  }

  .cycle-and-price {
    display: flex;
    justify-content: space-between;
    font-size: 25rpx;
    color: #6c6c6c;
    margin-top: 10rpx;

    .cycle {
      width: 80%;
    }

    .price {
    }
  }

  .project-row {
    display: flex;
    align-items: center;
    margin-top: 36rpx;

    .img {
      width: 136rpx;
      height: 136rpx;
      border-radius: 20rpx;
    }

    .name {
      color: #232323;
      font-size: 32rpx;
      font-weight: bold;
      margin-left: 24rpx;
    }
  }

  .info-row {
    display: flex;
    margin-top: 40rpx;

    .name {
      width: 136rpx;
      color: rgba(35, 35, 35, 0.7);
      font-size: 26rpx;
    }

    .value {
      color: #232323;
      font-size: 26rpx;
    }
  }

  .div-line {
    width: 100%;
    height: 2rpx;
    background: #f8f8f8;
    margin-top: 40rpx;
  }

  .price-and-pay {
    display: flex;
    align-items: center;
    margin-top: 20rpx;

    .left {
      display: flex;
      align-items: center;
      flex: 1;
    }

    .cancel-btn {
      width: 150rpx;
      height: 60rpx;
      border: solid 2rpx rgba(35, 35, 35, 0.26);
      border-radius: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      color: rgba(35, 35, 35, 0.8);
      font-size: 26rpx;
      margin-left: 8rpx;
      margin-right: 8rpx;
    }

    .ok-btn {
      width: 150rpx;
      height: 60rpx;
      border: solid 2rpx #0bc5ae;
      border-radius: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #0bc5ae;
      font-size: 26rpx;
      margin-left: 8rpx;
      margin-right: 8rpx;
    }
  }
}

.del-btn {
  width: 60rpx;
  height: 40rpx;
  border: solid 2rpx #c5070a;
  border-radius: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c5070a;
  font-size: 14rpx;
  margin-left: 8rpx;
  margin-right: 8rpx;
}

.service-btn {
  display: flex;
  justify-content: flex-end;
  margin-top: 20rpx;
  flex-wrap: wrap;
}

.service-btn .my-btn:not(:last-child) {
  margin-right: 10rpx;
}

.my-btn {
  min-width: 140rpx;
  height: 58rpx;
  line-height: 58rpx;
  border: 1rpx solid #d0d0d0;
  border-radius: 40rpx;
  color: #787878;
  text-align: center;
}

.btn-green {
  border-color: #04bdb3;
  color: #04bdb3;
}

.editBtn {
  position: absolute;
  right: 20rpx;
  top: 10rpx;
  width: 50rpx;
  height: 50rpx;
  background: url(https://bedfamily.eos.xian-2.cmecloud.cn/profile/xiaochengxu/static/icon_edit.png)
    no-repeat center center;
  background-size: 100% 100%;
}

.delBtn {
  position: absolute;
  right: 20rpx;
  bottom: 10rpx;
  width: 50rpx;
  height: 50rpx;
  background: url(https://bedfamily.eos.xian-2.cmecloud.cn/profile/xiaochengxu/static/icon_del.png)
    no-repeat center center;
  background-size: 100% 100%;
}

.addPatient {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin: 30rpx;

  .add-icon {
    background: url(https://bedfamily.eos.xian-2.cmecloud.cn/profile/xiaochengxu/static/icon_add.png)
      no-repeat center center;
    width: 50rpx;
    height: 50rpx;
    background-size: 100% 100%;
  }
}

.service-popup-view {
  width: 100%;
  background: white;
  padding: 40rpx;
  box-sizing: border-box;
  border-top-left-radius: 24rpx;
  border-top-right-radius: 24rpx;
  display: flex;
  flex-direction: column;
  position: relative;
  .title-view {
    position: relative;
    display: flex;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    padding: 10rpx 0;

    .title {
      color: #232323;
      font-size: 32rpx;
      font-weight: bold;
    }

    .close-btn-view {
      width: 80rpx;
      height: 80rpx;
      position: absolute;
      display: flex;
      align-items: center;
      justify-content: center;
      right: 0;

      .close-btn {
        width: 36rpx;
        height: 36rpx;
      }
    }
  }

  scroll-view {
    width: 100%;
    height: 70vh;
  }

  .item {
    width: 100%;
    display: flex;
    align-items: center;
    border-bottom: solid 2rpx #f8f8f8;
    padding-top: 36rpx;
    padding-bottom: 36rpx;

    .left-view {
      image {
        width: 120rpx;
        height: 120rpx;
        border-radius: 20rpx;
      }
    }

    .right-view {
      flex: 1;
      margin-left: 10rpx;
      display: flex;
      flex-direction: column;
      justify-content: space-around;

      .name-view {
        display: flex;
        color: #232323;
        font-size: 30rpx;
        font-weight: bold;
      }

      .adder-view {
        color: rgba(35, 35, 35, 0.5);
        font-size: 24rpx;
      }
    }
  }
}

.form-item-row {
  width: 100%;
  min-height: 120rpx;
  padding-left: 30rpx;
  padding-right: 30rpx;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .label {
    color: #232323;
    font-size: 32rpx;
    white-space: nowrap;
  }

  .small-label {
    color: #232323;
    font-size: 32rpx;
  }

  .required-label::after {
    content: "*";
    color: #e74242;
    font-size: 30rpx;
    margin-left: 4rpx;
  }

  .selector-text {
    color: #232323;
  }

  input {
    text-align: end;
  }
}

.save-btn {
  width: 100%;
  height: 88rpx;
  background: #0bc5ae;
  border-radius: 48rpx;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30rpx;
}

.bottom-view {
  width: 100%;
  padding: 30rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  // position: absolute;
  // bottom: 0;
}
.upload-id-card-view {
  width: 100%;
  display: flex;
  flex-direction: column;
  padding: 30rpx;
  box-sizing: border-box;

  .title {
    color: #232323;
    font-size: 32rpx;
  }

  .card-view {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 32rpx;
  }

  .card-item {
    display: flex;
    flex-direction: column;
    align-items: center;

    .card-img {
      width: 330rpx;
      height: 200rpx;
    }

    .tip-text {
      color: rgba(35, 35, 35, 0.8);
      font-size: 24rpx;
      margin-top: 28rpx;
    }
  }
}
</style>
